<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;

class adminModel extends Model
{

    protected $table = 'admin';
    protected $primaryKey = 'id';
    protected $appends = ['role'];

    public function checkUsername($username)
    {
        return $this->where('username', '=', $username)->exists();
    }

    public function checkStatus($username)
    {
        return $this->where('username', '=', $username)->where('lockuntil', '<', time())->where('status', '=', 1)->exists();
    }

    public function checkPassword($username, $password)
    {
        return $this->where('username', $username)->where('password', md5($password))->exists();
    }

    public function getRolename($roles_id)
    {
        return DB::table('admin_roles')->where('id', $roles_id)->value('name');
    }

    public function getRoleAttribute()
    {
        return DB::table('admin_roles')->where('id', $this->attributes['roles_id'])->value('name');
    }

    public function setUserLogin($username, $password)
    {
        if ($user = $this->where('username', $username)->where('password', md5($password))->first()) {
            $rows = [
                'logintimes' => intval($user->logintimes) + 1,
                'logined_at' => date('Y-m-d H:i:s'),
            ];
            $this->where('id', $user->id)->update($rows);
            if (empty($user->token)) {
                $token = md5($user->id . $user->group_id . $user->username . $user->logined_at . rand(10000, 99999));
                DB::table('admin')->where('id', $user->id)->update(['token' => $token]);
            } else {
                $token = $user->token;
            }
            forget('auths_' . $user->id);
            $data = [
                'user_id'  => $user->id,
                'roles_id' => $user->roles_id,
                'username' => $user->username,
                'phone'    => $user->phone,
                'avatar'   => $user->avatar
            ];
            global $auth;
            $auth = new Auth(_RBACCookieKey_);
            $auth->login($data);
            $auth->write();
            return $auth->isLogin();
        } else {
            return false;
        }
    }

    public function getRoles()
    {
        $rows = DB::table('admin_roles')->select('id', 'rolename')->get();

        return $rows;
    }

}
